﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace DIY_IOC_NEW.IOCS
{
    public class ServiceCollection
    {
        private Dictionary<string, object> IOCS = new Dictionary<string, object>();

        public ServiceCollection()
        {
            Assembly assembly = Assembly.Load("DIY_IOC_NEW");
            Type[] types = assembly.GetTypes();
            foreach (Type type in types)
            {
                IOCService? iOCService = type.GetCustomAttribute<IOCService>();
                if (iOCService != null)
                {
                    object? _object = Activator.CreateInstance(type);

                    PropertyInfo[] propertyInfos = type.GetProperties();
                    foreach (PropertyInfo propertyInfo in propertyInfos)
                    {
                        foreach(Type ty in types)
                        {
                            if (propertyInfo.PropertyType.Equals(ty))
                            {
                                object? _objectValue = Activator.CreateInstance(ty);
                                propertyInfo.SetValue(_object, _objectValue);
                            }
                        }
                    }

                    IOCS.Add(type.FullName, _object);
                }
            }
        }

        public object GetObject(string fullName)
        {
            return IOCS[fullName];
        }
    }
}
